<template>
  <el-dialog
    v-model="model['isShow']"
    :close-on-click-modal="false"
    :title="model['isEdit'] ? '修改地图' : '新增地图'"
    destroy-on-close
    width="50%"
    @open="openClick"
  >
    <el-form
      ref="ruleFormRef"
      :model="imageData"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      status-icon
      scroll-to-error
    >
      <el-form-item label="地图编号" prop="number">
        <el-input
          v-model="imageData.number"
          maxlength="8"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="地图名称" prop="name">
        <el-input
          v-model="imageData.name"
          maxlength="10"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="地图文件" prop="file">
        <!-- action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15" -->
        <!-- <el-upload
          v-model:file-list="fileList"
          class="upload-demo" 
          action
          :on-change="handleChange"
        >
          <el-button type="primary">点击上传</el-button>
          <template #tip>
            <div class="el-upload__tip">
              jpg/png files with a size less than 500kb
            </div>
          </template>
        </el-upload> -->
        <el-upload
          action="#"
          list-type="picture-card"
          :limit="1"
          :auto-upload="false"
          :on-change="handleChange"
        >
          <el-icon><Plus /></el-icon>

          <template #file="{ file }">
            <div>
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-preview"
                  @click="handlePictureCardPreview(file)"
                >
                  <el-icon><zoom-in /></el-icon>
                </span>
                <!-- 下载 -->
                <!-- <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleDownload(file)"
                >
                  <el-icon><Download /></el-icon>
                </span> -->
                <span
                  v-if="!disabled"
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <el-icon><Delete /></el-icon>
                </span>
              </span>
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="地图坐标" prop="coordinate">
        <div class="flex flex-col">
          <el-form-item label="经度" prop="longitude">
            <el-input
              v-model="imageData.longitude"
              placeholder="请输入坐标经度"
            />
          </el-form-item>
          <el-form-item label="纬度" prop="name" class="mt-3">
            <el-input
              v-model="imageData.latitude"
              placeholder="请输入坐标纬度"
            />
          </el-form-item>
        </div>
      </el-form-item>

      <el-form-item label="指北信息" prop="information">
        <el-input
          v-model="imageData.information"
          placeholder="请输入指北角度"
        />
      </el-form-item>
      <el-form-item label="初始角度" prop="visualAngle">
        <el-input
          v-model="imageData.visualAngle"
          placeholder="请输入初始角度"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="saveClick">保存</el-button>
        <el-button @click="model.isShow = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import message from "@/hooks/message";
import type { UploadProps, UploadUserFile, UploadFile } from "element-plus";
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";
import { addDataList, EditDataList } from "@/api/uploadMap";

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const disabled = ref(false);

interface Emits {
  (e: "saveChange", val: Boolean): void;
}
const emit = defineEmits<Emits>();
const model = defineModel({ default: { isShow: false, isEdit: false } });
const props = defineProps({
  soleItem: {
    type: Object,
    default: {},
  },
});
// const { soleItem } = props;
const rules = reactive<any>([]);
const imageData = ref<any>({});
const uploadImage = () => {};

const openClick = () => {
  const { coordinate } = props.soleItem;
  const [longitude, latitude] = coordinate.split(",");
  imageData.value = JSON.parse(JSON.stringify(props.soleItem));
  imageData.value["longitude"] = longitude;
  imageData.value["latitude"] = latitude;
};
// -----------------文件上传--------------------

const handleRemove = (file: UploadFile) => {
  console.log(file);
};

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!;
  dialogVisible.value = true;
};

// const handleDownload = (file: UploadFile) => {
//   console.log(file);
// };
const handleChange: UploadProps["onChange"] = (uploadFile: UploadFile) => {
  // 创建 FileReader 实例
  const reader = new FileReader();
  // 直接从文件创建 URL
  if (uploadFile.raw) {
    const objectUrl = URL.createObjectURL(uploadFile.raw);
    dialogImageUrl.value = objectUrl;
    imageData.value.fileUrl = objectUrl;
    imageData.value.file = uploadFile.raw;
  }
  // 当不再需要这个 URL 时，记得释放它
  return () => {
    URL.revokeObjectURL(dialogImageUrl.value);
  };
  // reader.onload = (e) => {
  //   // 读取完成后的回调，e.target.result 包含图片的 base64 数据
  //   if (e.target?.result) {
  //     // 将图片 URL 保存到 dialogImageUrl 或其他需要的变量中
  //     dialogImageUrl.value = e.target.result as string;
  //     // 如果需要保存到表单数据中
  //     imageData.file = uploadFile.raw;
  //     imageData.fileUrl = e.target.result;
  //   }
  // };

  // // 开始读取文件
  // if (uploadFile.raw) {
  //   reader.readAsDataURL(uploadFile.raw);
  // }
};
// --------------------文件上传结束-----------------
const saveClick = () => {
  const { id, number, name, information, visualAngle, longitude, latitude } =
    imageData.value;
  if (
    !number ||
    !name ||
    !information ||
    !visualAngle ||
    !longitude ||
    !latitude
  )
    return message("请补充完整信息", "error");

  imageData.value.coordinate = `${longitude},${latitude}`;
  const portName = id ? EditDataList : addDataList;

  portName(imageData.value)
    .then((res) => {
      if (res.code === 200) {
        message(res.data || "操作成功", "success");
        model.value.isShow = false;
      }
    })
    .finally(() => {
      emit("saveChange", true);
    });
};
</script>

<style lang="scss" scoped></style>
